package com.mazihao.emos.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.mazihao.emos.common.util.AjaxResult;
import com.mazihao.emos.config.SystemConstants;
import com.mazihao.emos.config.shiro.JwtUtil;
import com.mazihao.emos.controller.form.CheckinForm;
import com.mazihao.emos.controller.form.SearchMonthCheckinForm;
import com.mazihao.emos.exception.EmosException;
import com.mazihao.emos.service.CheckinService;
import com.mazihao.emos.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.HashMap;

@RestController
@RequestMapping("/checkin")
@Api("签到模块web接口")
@Slf4j
public class CheckinController {
    @Resource
    private JwtUtil jwtUtil;

    @Resource
    private CheckinService checkinService;

    @Resource
    private UserService userService;

    @Resource
    private SystemConstants constants;

    @GetMapping("/validCanCheckIn")
    @ApiOperation("查看用户今天是否可以签到")
    public AjaxResult validCanCheckIn(@RequestHeader("token") String token) {
        int userId = jwtUtil.getUserId(token);
        String result = checkinService.validCanCheckIn(userId, DateUtil.today());
        return AjaxResult.ok(result);
    }

    @PostMapping("/checkin")
    @ApiOperation("签到")
    public AjaxResult checkin(@Valid CheckinForm form, @RequestHeader("token") String token) {
        int userId = jwtUtil.getUserId(token);
        HashMap<String,Object> param = new HashMap<>();
        param.put("userId", userId);
        param.put("address", form.getAddress());
        param.put("country", form.getCountry());
        param.put("province", form.getProvince());
        param.put("city", form.getCity());
        param.put("district", form.getDistrict());
        checkinService.checkin(param);
        return AjaxResult.ok("签到成功");
    }

    @GetMapping("/searchTodayCheckin")
    @ApiOperation("查询用户当日签到数据")
    public HashMap<String, Object> searchTodayCheckin(@RequestHeader("token") String token) {
        // 从token中解析用户ID
        int userId = jwtUtil.getUserId(token);

        // 查询用户当日的签到数据
        HashMap map = checkinService.searchTodayCheckin(userId);

        // 将考勤时间和下班时间常量放入返回结果中
        map.put("attendanceTime", constants.attendanceTime);
        map.put("closingTime", constants.closingTime);

        // 查询用户累计的签到天数
        long days = checkinService.searchCheckinDays(userId);
        map.put("checkinDays", days);

        // 查询用户入职日期，并判断周的开始日期是否在入职之前
        DateTime hireDate = DateUtil.parse(userService.searchUserHireDate(userId));
        // 本周开始日期
        DateTime startDate = DateUtil.beginOfWeek(DateUtil.date());
        // 如果周开始日期早于入职日期，则设置为入职日期
        if (startDate.isBefore(hireDate)) {
            startDate = hireDate;
        }
        // 本周结束日期
        DateTime endDate = DateUtil.endOfWeek(DateUtil.date());

        // 构建查询本周签到情况的参数
        HashMap<String, Object> param = new HashMap<>();
        // 设置本周开始日期
        param.put("startDate", startDate.toString());
        // 设置本周结束日期
        param.put("endDate", endDate.toString());
        // 用户ID
        param.put("userId", userId);

        // 查询本周签到情况, 将本周签到数据添加到结果集中
        map.put("weekCheckin", checkinService.searchWeekCheckin(param));

        // 返回结果封装在AjaxResult对象中
        return AjaxResult.ok().put("result", map);
    }

    @PostMapping("/searchMonthCheckin")
    @ApiOperation("查询用户当月签到数据")
    public AjaxResult searchMonthCheckin(@Valid @RequestBody SearchMonthCheckinForm form,
                                         @RequestHeader("token") String token) {
        int userId = jwtUtil.getUserId(token);
        DateTime hireDate = DateUtil.parse(userService.searchUserHireDate(userId));
        String month = form.getMonth() < 10 ? "0" + form.getMonth() : form.getMonth().toString();
        DateTime startDate = DateUtil.parseDate(form.getYear() + "-" + month + "-01");
        if (startDate.isBefore(DateUtil.beginOfMonth(hireDate))) {
            throw new EmosException("只能查询考勤之后日期的数据");
        }
        if (startDate.isBefore(hireDate)) {
            startDate = hireDate;
        }
        DateTime endDate = DateUtil.endOfMonth(startDate);
        HashMap<String, Object> param = new HashMap<>();
        param.put("userId", userId);
        param.put("startDate", startDate.toString());
        param.put("endDate", endDate.toString());
        ArrayList<HashMap> list = checkinService.searchMonthCheckin(param);
        int sum_1 = 0;
        int sum_2 = 0;
        int sum_3 = 0;
        for(HashMap<String, String> one : list){
            String type = one.get("type");
            String status = one.get("status");
            if ("工作日".equals(type)) {
                if ("正常".equals(status)) {
                    sum_1++;
                } else if ("迟到".equals(status)) {
                    sum_2++;
                } else if ("缺勤".equals(status)) {
                    sum_3++;
                }
            }
        }
        return AjaxResult.ok().put("list", list).put("sum_1", sum_1).put("sum_2", sum_2).put("sum_3", sum_3);
    }

}
